package com.onec.service.route.service.api;


import com.onec.service.api.dto.request.route.RouteReq;
import com.onec.service.api.dto.response.route.RouteResp;
import com.onec.service.api.enums.ServiceTradeEnum;
import com.onec.service.api.enums.SystemTypeEnum;
import com.onec.service.api.enums.error.RouteErrorEnum;
import com.onec.service.api.service.route.RouteRiskApiService;
import com.onec.service.api.utils.ValidatorUtils;
import com.onec.service.route.entity.RouteChannelBank;
import com.onec.service.route.entity.RouteChannelInfo;
import com.onec.service.route.service.base.BaseRouteRiskService;
import com.onec.service.route.service.base.BaseTradeConfigDefaultService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author onec
 */
@DubboService(version = "1.0.1", timeout = 6000)
@Slf4j
public class RouteRiskApiServiceImpl extends BaseRouteRiskService implements RouteRiskApiService {


    /**
     * 交易控制信息：
     *
     * @param routeReq r
     * @return RouteResp
     */
    @Override
    public RouteResp getRouteByTradeRisk(RouteReq routeReq) {

        ValidatorUtils.validateEntity(routeReq);
        businessInfoService.isSuccessBusiness(routeReq.getBusinessNo());

        this.checkRouteRiskType(routeReq, SystemTypeEnum.TRADE_CONFIG);

        // 路由通道信息：
        List<RouteChannelInfo> routeChannelInfos = routeChannelInfoService.findByBusinessNo(routeReq.getBusinessNo());
        // 配置银行费率：
        List<RouteChannelInfo> routeChannelInfoList = routeChannelInfos
                .stream()
                .filter(e -> {
                    log.info("当前业务:{}，获取的通道：{}，费率类型：{}", e.getBusinessNo(), e.getChannelNo(), e.getFeeType());
                    if (Objects.equals(SystemTypeEnum.BANK_FEE, e.getFeeType())) {
                        RouteChannelBank routeChannelBank = routeChannelBankService
                                .getRouteChannelBank(routeReq.getBankCode(), e.getId());
                        if (Optional.ofNullable(routeChannelBank).isPresent()) {
                            e.setRate(routeChannelBank.getRate());
                            e.setFee(routeChannelBank.getFee());
                        }
                    }
                    return true;
                }).collect(Collectors.toList());

        BigDecimal amount = routeReq.getAmount();
        Map<BigDecimal, RouteChannelInfo> feeMap = routeChannelInfoList
                .stream()
                .collect(Collectors.toMap(one -> amount.multiply(one.getRate()).add(one.getFee()), e -> e));
        // 排序：
        List<Map.Entry<BigDecimal, RouteChannelInfo>> entryList = feeMap
                .entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry::getKey))
                .collect(Collectors.toList());

        RouteChannelInfo routeChannelInfo = entryList.get(0).getValue();
        // 通道已经配置成功：

        return respRouteChannelInfo(routeReq, routeChannelInfo);
    }

    /**
     * 商户注册，修改等风控限制：
     *
     * @param routeReq
     * @return
     */
    @Override
    public RouteResp getRouteByCustomerRisk(RouteReq routeReq) {
        ValidatorUtils.validateEntity(routeReq);
        businessInfoService.isSuccessBusiness(routeReq.getBusinessNo());
        // 业务配置的规则：
        this.checkRouteRiskType(routeReq, SystemTypeEnum.MERCHANT_CONFIG);

        return respErrorRoute(RouteErrorEnum.SUCCESS);
    }

    /**
     * 获取上游通道
     *
     * @param routeReq
     * @return
     */
    @Override
    public RouteResp getNeedRegisterChannelList(RouteReq routeReq) {
        ValidatorUtils.validateEntity(routeReq);
        businessInfoService.isSuccessBusiness(routeReq.getBusinessNo());

        // 风控
        this.checkRouteRiskType(routeReq, SystemTypeEnum.MERCHANT_CONFIG);

        // 路由通道信息：
        List<RouteChannelInfo> routeChannelInfos = routeChannelInfoService.findByBusinessNo(routeReq.getBusinessNo());
        List<String> channelNoList = routeChannelInfos
                .stream()
                .filter(RouteChannelInfo::isNeedRegister)
                .map(RouteChannelInfo::getChannelNo)
                .collect(Collectors.toList());
        if (channelNoList.isEmpty()) {
            return respErrorRoute(RouteErrorEnum.MERCHANT_NOT_NEED_REDISGER);
        }
        // 返回信息
        RouteChannelInfo routeChannelInfo = routeChannelInfos.get(0);
        RouteResp routeResp = respRouteChannelInfo(routeReq, routeChannelInfo);
        routeResp.setChannelNoList(channelNoList);
        return routeResp;
    }

    /**
     * 自动新增一条规则配置：
     *
     * @param routeReq         规则信息：
     * @param serviceTradeEnum serviceTradeEnum ：规则配置
     * @return
     */
    @Override
    public boolean addRiskRouteInfo(RouteReq routeReq, ServiceTradeEnum serviceTradeEnum) {
        BaseTradeConfigDefaultService baseRouteRiskService = applicationContext
                .getBean(serviceTradeEnum.name(), BaseTradeConfigDefaultService.class);
        return baseRouteRiskService.afterExecute(routeReq);
    }


}
